/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2015-5-17 下午1:40:02
 */
package xiaojian.toolkit.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.base.Sender;
import xiaojian.toolkit.base.TransportUtils;

import com.google.common.base.Preconditions;

/**
 * @author <a href="mailto:caoxiaojian@wasu.com>xiaojian.cao</a>
 * 
 */
public abstract class AbstractTcpReqHandler<Q extends AbstractRequest, R extends AbstractResponse> extends AbstractReqHandler<AbstractRequest> {

	private static final Logger logger = LoggerFactory
			.getLogger(AbstractTcpReqHandler.class);

	/**
	 * 子类必须生成一个回应的对象。
	 * 
	 * @param request
	 * @return
	 */
	protected abstract R newResponse(Q request);
	
	/**
	 * 让子类去处理处理过程中异常。
	 * 
	 * @param exception
	 */
	protected abstract void processException(Exception exception, AbstractRequest request, AbstractResponse response);
	
	/**
	 * @see com.wasu.upm.commons.handler.ReqHandler#doReq(com.wasu.upm.commons.AbstractUPMRequest)
	 */
	protected abstract void doReq1(Q request,
			R response);

	public void doReq0(AbstractRequest request) {
		Preconditions.checkArgument(request != null
				&& request.getIdentification() != null);
		AbstractResponse response = newResponse((Q)request);

		if (response == null) {
			logger.error("Pls implement method[newResponse(AbstractUPMRequest request)], request["
					+ request + "].");
			return;
		}

		try {
			doReq1((Q)request, (R)response);
		} catch (Exception exception) {
			logger.error("Prorcess reqest[" + request + "] fail.", exception);
			processException(exception, request, response);
		}

		send(request, response);
	}
	
	protected void send(AbstractRequest request, AbstractResponse response) {
		response.setIdentification(request.getIdentification());
		Sender<AbstractResponse> sender = TransportUtils.getSenderOf(request);
		if (logger.isDebugEnabled()) {
			logger.debug("SendClientRespState={}", response);
		}
		if (sender != null) {
			sender.send(response);
		} else {
			logger.error("getSender error!");
		}
	}

}
